package com.ferris.redbook.controller;

import com.ferris.redbook.dto.request.LoginRequest;
import com.ferris.redbook.dto.request.RegisterRequest;
import com.ferris.redbook.dto.response.UserResponse;
import com.ferris.redbook.service.AuthService;
import com.ferris.redbook.service.UserService;
import com.ferris.redbook.util.AjaxResult;
import com.ferris.redbook.util.UserContext;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody LoginRequest request) {
        log.info("用户登录：{}", request);
        return authService.login(request);
    }
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody RegisterRequest request) {
        return authService.register(request);
    }


    /**
     * 获取当前用户信息
     * 方法: GET
     * URL: /auth/me
     */
    @GetMapping("/me")
    public AjaxResult getCurrentUser() {
        log.info("获取当前用户信息");
        return Optional.ofNullable(UserContext.getUserId())
                .map(userId -> {
                    UserResponse userInfo = userService.getCurrentUserInfo(userId);
                    return Optional.ofNullable(userInfo)
                            .map(AjaxResult::success)
                            .orElse(AjaxResult.error("用户不存在"));
                })
                .orElse(AjaxResult.unauthorized("用户未登录"));
    }

}